package com.lizk.graph.weight;

import com.lizk.tools.base.Checks;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lizhikui
 * @date 2020/2/15 14:25
 */
public class AdjacencyList implements WeightGraph<Edge<Integer>> {
    int column4Iterator;
    int row4Iterator;
    boolean directed;
    List<Edge<Integer>>[] g ;

    public AdjacencyList(int n, boolean directed){
        g = new List[n];
        this.directed = directed;

        for (int i = 0; i < g.length; i++) {
            g[i] = new ArrayList<>();
        }
    }

    @Override
    public void iterator(int row){
        this.row4Iterator = row;
        this.column4Iterator = 0;
    }

    @Override
    public boolean hasNext() {
        return column4Iterator < g[row4Iterator].size();
    }

    @Override
    public Edge<Integer> next() {
        return g[row4Iterator].get(column4Iterator++);
    }

    @Override
    public void addEdge(Edge<Integer> edge) {
        int row = edge.getFrom();
        int col = edge.getTo();
        Checks.checkNotNull(edge);
        if (!hasEdge(edge)){
            g[row].add(new Edge<>(row,col,edge.getWeight()));
            if (row != col && !directed){
                g[col].add(new Edge<>(col,row,edge.getWeight()));
            }
        }
    }

    @Override
    public int size() {
        return g.length;
    }

    @Override
    public boolean hasEdge(Edge<Integer> edge) {
        Checks.checkNotNull(edge);
        return g[edge.getFrom()].contains(edge);
    }
}





